package com.ccl.iot.publics;import java.lang.reflect.Constructor;

public class ClassManager {
	public static boolean IsSubClass(Class<?> aSuperType, Class<?> aSubType){
		if (aSuperType != null && aSubType != null){
			if (aSubType != aSuperType){
				Class<?> tType = aSubType;
				
				if (aSuperType.isInterface()){
					Class<?> tInterface[] = tType.getInterfaces();
					
					if (tInterface != null && tInterface.length > 0){
						for (int i = 0; i < tInterface.length; i++){
							if (tInterface[i] == aSuperType){
								return true;
							}else{
								if (IsSubClass(aSuperType, tInterface[i])){
									return true;
								}
							}
						}
					}
					
					while((tType = tType.getSuperclass()) != null && tType != Object.class){
						if (IsSubClass(aSuperType, tType)){
							return true;
						}
					}
				}else{
					while((tType = tType.getSuperclass()) != null && tType != Object.class){
						if (tType == aSuperType){
							return true;
						}
					}
				}				
			}else{
				return true;
			}
		}
		
		return false;
	}
	
	public static Class<?> GetObjectTypeClass(Class<?> aClass){
		if (aClass == byte.class){
			return Byte.class;
		}else if (aClass == short.class){
			return Short.class;
		}else if (aClass == int.class){
			return Integer.class;
		}else if (aClass == long.class){
			return Long.class;
		}else if (aClass == float.class){
			return Float.class;
		}else if (aClass == double.class){
			return Double.class;
		}else{
			return aClass;
		}
	}

	public static int GetMinConstructorCount(Class<?> aClass){
		if (aClass != null){
				Constructor<?> tCons[] = aClass.getDeclaredConstructors();
				
				if (tCons != null && tCons.length > 0){
					int tMin = -1;
					
					for (int i = 0; i < tCons.length; i++){
						Class<?> tParams[] = tCons[i].getParameterTypes();
						
						if (tParams != null){
							if (tMin == -1 || tMin > tParams.length){
								tMin = tParams.length;
							}
						}
					}
			}
		}
		
		return -1;
	}	

	public static Constructor<?> FindConstructor(Class<?> aClass, Object ... aParams){
		if (aClass != null){
			int tParamCount = 0;
			
			if (aParams != null){
				Constructor<?> tCons[] = aClass.getDeclaredConstructors();
				
				tParamCount = aParams.length;
				
				if (tCons != null){
					int i, j;
					
					for (i = 0; i < tCons.length; i++){
						Class<?> tParams[] = tCons[i].getParameterTypes();
						
						if (tParams != null && tParams.length == tParamCount){
							for (j = 0; j < tParams.length; j++){
								if (GetObjectTypeClass(tParams[j])!= GetObjectTypeClass(aParams[j].getClass())){
									break;
								}
							}
							
							if (j == tParams.length){
								break;
							}
						}
					}
					
					if (i != tCons.length){
						return tCons[i];
					}
				}				
			}
		}
		
		return null;
	}	
}
